import { Category } from 'server/models/Category'
import { successResponse, errorResponse } from 'server/utils/response'

export default defineEventHandler(async (event) => {
  try {
    const categoryId = getRouterParam(event, 'id')
    if (!categoryId) {
      return errorResponse('参数错误', '分类ID不能为空')
    }

    // 检查分类是否存在
    const existingCategory = await Category.getById(categoryId)
    if (!existingCategory) {
      return errorResponse('分类不存在', '指定的分类不存在')
    }

    const body = await readBody(event)
    const { name, description, color, icon, status } = body

    // 验证必需字段
    if (!name || !name.trim()) {
      return errorResponse('参数错误', '分类名称不能为空')
    }

    // 生成新的 slug（如果名称改变了）
    let slug = existingCategory.slug
    if (name.trim() !== existingCategory.name) {
      slug = name.toLowerCase()
        .replace(/\s+/g, '-')
        .replace(/[^\w\-]+/g, '')
        .replace(/\-\-+/g, '-')
        .replace(/^-+/, '')
        .replace(/-+$/, '')
      
      // 如果slug为空，使用原始slug或生成默认值
      if (!slug) {
        slug = existingCategory.slug || 'default-category'
      }
    }

    const updateData = {
      name: name.trim(),
      slug,
      description: description?.trim() || '',
      color: color ? color.substring(0, 7) : '#1890ff', // 限制为7个字符
      icon: icon || 'fa:folder',
      status: status || 'active'
    }

    const success = await Category.updateCategory(categoryId, updateData)
    
    if (!success) {
      return errorResponse('更新失败', '分类更新失败')
    }

    // 获取更新后的分类信息
    const updatedCategory = await Category.getById(categoryId)
    
    if (!updatedCategory) {
      return errorResponse('更新失败', '无法获取更新后的分类信息')
    }

    // 格式化返回数据
    const formattedCategory = {
      id: updatedCategory.id?.toString() || '',
      name: updatedCategory.name,
      slug: updatedCategory.slug,
      description: updatedCategory.description || '',
      color: updatedCategory.color || '#1890ff',
      icon: updatedCategory.icon || 'fa:folder',
      postCount: updatedCategory.post_count || 0,
      status: updatedCategory.status,
      createdAt: updatedCategory.created_at ? new Date(updatedCategory.created_at).toISOString().split('T')[0] : '',
      updatedAt: updatedCategory.updated_at ? new Date(updatedCategory.updated_at).toISOString().split('T')[0] : ''
    }

    return successResponse(formattedCategory, '分类更新成功')
  } catch (error) {
    console.error('更新分类失败:', error)
    return errorResponse('更新分类失败', error instanceof Error ? error.message : '未知错误')
  }
})